package com.gxg.services;

import java.io.*;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 * By 李朋飞
 **/
@Service
public class JudgeServerService {
    @Autowired
    RestTemplate restTemplate;
    public String judgeServer(String content,String type){
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("content",content);
        paramMap.add("type",type);
        System.out.println("内容："+content);
        System.out.println("类型："+type);
        String url = "http://47.101.209.39:8801/judgeByString";
        return restTemplate.postForObject(url, paramMap, String.class);
    }
    public String judgeServerByFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.split("\\.")[1];
        String fileNameExpectType = fileName.split("\\.")[0];
        File fileTemp = File.createTempFile(fileNameExpectType,"."+fileType);
        try {
            file.transferTo(fileTemp);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        System.out.println(fileTemp.getName());
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        FileSystemResource resource = new FileSystemResource(fileTemp);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("file",resource);
        String url = "http://47.101.209.39:8801/judgeByFile";
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(paramMap, headers);
        return restTemplate.postForObject(url, files, String.class);
    }
}
